package com.example.demo.util;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.apache.commons.codec.digest.DigestUtils;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wn
 * @date 2022年09月19日 15:14
 */
public class GroovyUtils {
    private static final Logger logger = LoggerFactory.getLogger(GroovyUtils.class);
    private static GroovyShell groovyShell = new GroovyShell();

    private static Map<String, Script> scriptCache = new ConcurrentHashMap<>();

    public GroovyUtils() {
        logger.info("1111111111111");
        Binding binding = new Binding();
        binding.setVariable("log", logger);
        groovyShell = new GroovyShell(binding);
    }

    public static <T> T invoke(String scriptText, String function, Object... objects) throws Exception {
        logger.info("2222222222222222222");
        Script script;
        String cacheKey = DigestUtils.md5Hex(scriptText);

        if (scriptCache.containsKey(cacheKey)) {
            script = scriptCache.get(cacheKey);
        } else {
            script = groovyShell.parse(scriptText);
            scriptCache.put(cacheKey, script);
        }

        return (T) InvokerHelper.invokeMethod(script, function, objects);
    }
}

